package cn.pegasus.teamwork.appinterface.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;

import cn.iyizhan.teamwork.base.util.ValidatorUtil;
import cn.pegasus.teamwork.appinterface.session.MySessionContext;

/**
 * 
 * @ClassName: BasePathIntecaptor
 * @Description: 路径拦截器
 * @author buyuer
 * @date 2015年11月26日 下午3:25:30
 *
 */
public class BasePathIntecaptor extends HandlerInterceptorAdapter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private String requestPath = null; // 请求地址
    
    private Map<?, ?> inputParamMap = null; // 传入参数

    String userName ;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求参数
        String sessionId = request.getParameter("userCertificate");
        if (ValidatorUtil.isNotEmpty(sessionId)) {
            HttpSession session = MySessionContext.getInstance().getSession(sessionId);
            if (session != null) {
//                SysUcenterUserMain user = ((SessionVO) session.getAttribute("user")).getUserMain();
//                userName = user.getUserName();
            } else {
                userName = "匿名用户";
            }
        } else {
            userName = "匿名用户";
        }

        // 获取输入参数
        inputParamMap = request.getParameterMap();
        // 获取请求地址
        requestPath = request.getRequestURI();
        printOptLog();
        // 获取路径
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int port = request.getServerPort();
        String path = request.getContextPath();
        String basePath = scheme + "://" + serverName + ":" + port + path;
        // logger.info("basePath : " + basePath);
        request.setAttribute("basePath", basePath);
        return true;
    }

    /**
     * 
     * @Title：printOptLog
     * @Description: 输出日志
     * @author shaojian.yu
     * @date 2014年11月2日 下午4:47:09
     */
    private void printOptLog() {
        StringBuffer sb = new StringBuffer("\n\n");
        sb.append("-----------------------------------------------------------\n");
        sb.append("request URL : " + requestPath + " \n");
        sb.append("request PARAM : " + JSON.toJSONString(inputParamMap) + " \n\n");
        sb.append("-----------------------------------------------------------\n");

        logger.info(sb.toString());
    }
}